<template>
  <el-card>
    <div slot="header">
      <h3>修改供货信息</h3>
    </div>
    <div>
      <el-row type="flex" justify="end">
        <el-button
          v-if="showBtn('高级关联')"
          type="text"
          size="large"
          icon="el-icon-link"
          @click="handleSeniorAssociated"
        >高级关联</el-button
        >
        <el-button
          v-if="fromType !== 'single' && showBtn('关联商品')"
          type="text"
          size="large"
          @click="showlinkgoods"
          >关联商品</el-button
        >
        <el-button
          v-if="infoData.length > 0"
          type="text"
          size="large"
          @click="exportTable"
          :loading="exportLoading"
          >模板导出</el-button
        >
        <a
          ><Upload
            :show-upload-list="false"
            :format="['xlsx', 'xls', 'csv']"
            :before-upload="uploadBefore"
            :on-error="uploadError"
            :on-success="uploadSuccess"
            :on-format-error="formatError"
            :action="`${uploadBaseURL}sysback/supplyskurel/importTemplate`"
            ><el-button type="text" size="large">模板导入</el-button></Upload
          ></a
        >
        <template v-if="infoData.length > 0">
          <el-button
            type="text"
            size="large"
            @click="save"
            :loading="saveLoading"
            >暂存</el-button
          >
          <el-button
            type="text"
            size="large"
            @click="submit"
            :loading="submitLoading"
            >提交</el-button
          >
          <el-button
            v-if="recordNo"
            type="text"
            size="large"
            @click="$router.push({ name: 'chageFromManageList' })"
            >返回</el-button
          >
        </template>
      </el-row>
      <!-- 发起原因输入框 -->
      <LaunchReasonInput :reason.sync="launchReason" />
      <el-row class="item_wrap">
        <skus-table
          :loading="tableLoading"
          :data-source="infoData"
          :columns="infoColumns"
          :defaultMinWidth="120"
          @handleCancelSelect="handleCancelSelect"
        />
      </el-row>
      <FooterFields :recordNo="recordNo" />
    </div>
    <link-modal
      ref="link"
      :pageType="1"
      :dialog-visible="diaVisible"
      :column="linkColumns"
      :skuRows="skuRows"
      @returnList="getInfoData"
      @addSkuRows="addSkuRows"
      @removeSkuRows="removeSkuRows"
    />
    <SeniorLinkedDialog
      :visible.sync="seniorAssociated.visible"
      :columns="seniorAssociated.columns"
      :dataSource="seniorAssociated.dataSource"
      @seniorSearchResult="getSeniorResultFn"
    />
  </el-card>
</template>
<script>
import { ApiRequest, ApiRequestExportTable } from '@api/basePage';
import { mapGetters } from 'vuex';
import { getBtnsId } from '@/libs/btnsPermission';
import linkModal from '@/pages/commodity/commodityManage/chageFromManage/comps/linkModalForSupply';
import SkusTable from '@/components/skusTable';
import FooterFields from '@/pages/commodity/components/FooterFields';
import SeniorLinkedDialog from '@/components/SeniorLinkedDialog';
import LaunchReasonInput from '@/components/LaunchReasonInput';
import { getFooterFieldFn } from '@/pages/commodity/modules/utils';
import { generateUuid } from '@/utils/bizUtils';
import { EDIT_SUPPLY_INFO_AMOUNT } from '@/constants/exportAmountLimit';

export default {
  components: {
    linkModal,
    SkusTable,
    FooterFields,
    SeniorLinkedDialog,
    LaunchReasonInput
  },
  data () {
    return {
      launchReason: '', // 发起原因
      seniorAssociated: {
        visible: false,
        isSenior: false, // 是否是高级关联，true是，false为普通关联
        columns: [{
          label: '供应商编码',
          prop: 'supplyCode',
          type: 'textarea'
        },
        {
          label: 'SKU编码',
          prop: 'skuNo',
          type: 'textarea'
        }],
        dataSource: [{
          supplyCode: '',
          skuNo: ''
        }]
      },
      exportLoading: false, // 导出按钮loading
      saveLoading: false, // 暂存按钮loading
      submitLoading: false, // 提交按钮loading
      footerFields: {}, // 表尾字段
      skuRows: [],
      diaVisible: false, // 关联商品 弹窗
      tableLoading: false,
      supplierCode: '', // 供应商编码 - 模糊查询
      supplyName: '', // 供应商名称 - 模糊查询
      productName: '', // 关联弹窗 查询
      spuNo: '', // 关联弹窗 查询
      skuNoBy: '', // 关联弹窗 查询
      skuNo: '',
      goodsLoading1: true,
      goodsLoading2: true,
      tabsValue: 'linkno', // 切换tabs
      selectAllList: [],
      selectNoList: [],
      totalPage: 0,
      nowPage: 1,
      pageShow: 10,
      saveinfo: {},
      fromType: '',
      yesOrno: [
        {
          label: '是',
          value: '1'
        },
        {
          label: '否',
          value: '2'
        }
      ],
      linkColumns: [
        // 关联商品  表头
        {
          type: 'selection',
          width: 60,
          align: 'center'
        },
        {
          title: '供应商编码',
          key: 'supplierCode',
          minWidth: 150,
          align: 'center',
        },
        {
          title: '供应商名称',
          key: 'supplierName',
          minWidth: 150,
          align: 'center',
        },
        {
          title: '商品名称',
          key: 'productName',
          minWidth: 150,
          align: 'center',
        },
        {
          title: 'SPU编码',
          key: 'spuNo',
          minWidth: 150,
          align: 'center',
        },
        {
          title: 'SKU编码',
          key: 'skuNo',
          minWidth: 150,
        },
        {
          title: '规格参数',
          key: 'specDetailStr',
          minWidth: 150,
          align: 'center'
        },
        {
          title: '品牌',
          key: 'brandName',
          minWidth: 150,
          align: 'center'
        },
        {
          title: '操作',
          slot: 'action',
          align: 'center',
          fixed: 'right',
          minWidth: 100
        }
      ],
      infoColumns: [
        {
          title: '供应商编码',
          key: 'supplyUuid',
          align: 'center',
          fixed: 'left'
        },
        {
          title: '供应商名称',
          key: 'supplyName',
          fixed: 'left',
          align: 'center',
          render: (h, { row }) => {
            return row.supplyInfoDTO ? (
              <span>{row.supplyInfoDTO.supplyName}</span>
            ) : (
              ''
            );
          }
        },
        {
          title: '是否敏感',
          key: 'isPriceSensitive',
          fixed: 'left',
          align: 'center',
          render: (h, { row }) => {
            let isPriceSensitive = '';
            if (row.supplyProductInfo) {
              if (row.supplyProductInfo.isPriceSensitive == '1') {
                isPriceSensitive = '是'
              } else if (row.supplyProductInfo.isPriceSensitive == '2') {
                isPriceSensitive = '否'
              }
            }
            return <span>{ isPriceSensitive }</span>;
          }
        },
        {
          title: '商品管理区域',
          key: 'manageArea',
          align: 'center',
          render: (h, { row }) => {
            return row.supplyProductInfo ? (
              <span>{row.supplyProductInfo.manageArea}</span>
            ) : (
              ''
            );
          }
        },
        {
          title: '供货单位',
          key: 'supplyGoodsUnit',
          align: 'center',
          render: (h, { row }) => {
            return row.supplyProductInfo ? (
              <span>{row.supplyProductInfo.supplyGoodsUnit}</span>
            ) : (
              ''
            );
          }
        },
        { title: 'SKU编码', key: 'skuNo', align: 'center', minWidth: 150 },
        {
          title: '商品名称',
          key: 'productName',
          align: 'center',
          render: (h, { row }) => {
            return row.supplyProductInfo ? (
              <span>{row.supplyProductInfo.productName}</span>
            ) : (
              ''
            );
          }
        },
        {
          title: '规格',
          key: 'specDetailStr',
          align: 'center',
          render: (h, { row }) => {
            return row.supplyProductInfo ? (
              <span>{row.supplyProductInfo.specDetailStr}</span>
            ) : (
              ''
            );
          }
        },
        {
          title: '厂商代码',
          key: 'factoryCode',
          align: 'center',
          minWidth: 150,
          type: 'input'
        },
        {
          title: '厂商名称',
          key: 'factoryName',
          align: 'center',
          minWidth: 150,
          type: 'input'
        },
        {
          title: '最小订货量',
          key: 'minOrderGoodsNum',
          align: 'center',
          minWidth: 150,
          type: 'input'
        },
        {
          title: '是否保修',
          key: 'warrantyStatus',
          align: 'center',
          type: 'select',
          options: [
            { label: '是', value: '1' },
            { label: '否', value: '2' }
          ]
        },
        {
          title: '保修天数',
          key: 'warrantyDay',
          align: 'center',
          minWidth: 150,
          type: 'input'
        },
        {
          title: '是否可换货',
          key: 'exchangeGoodsStatus',
          align: 'center',
          type: 'select',
          options: [
            { label: '是', value: '1' },
            { label: '否', value: '2' }
          ]
        },
        {
          title: '换货天数',
          key: 'exchangeGoodsDay',
          align: 'center',
          minWidth: 150,
          type: 'input'
        },
        {
          title: '换货条件',
          key: 'exchangeGoodsCondition',
          align: 'center',
          minWidth: 150,
          type: 'input'
        },
        {
          title: '是否可退货',
          key: 'returnGoodsStatus',
          align: 'center',
          type: 'select',
          options: [
            { label: '是', value: '1' },
            { label: '否', value: '2' }
          ]
        },
        {
          title: '退货天数',
          key: 'returnGoodsDay',
          align: 'center',
          minWidth: 150,
          type: 'input'
        },
        {
          title: '退货条件',
          key: 'returnGoodsCondition',
          align: 'center',
          minWidth: 150,
          type: 'input'
        },
        {
          title: '最小退换货量',
          key: 'minReOrExNum',
          align: 'center',
          minWidth: 150,
          type: 'input'
        },
        {
          title: '商品销售最小残次品',
          key: 'minSaleImperfectionsNum',
          align: 'center',
          minWidth: 170,
          type: 'input'
        },
        {
          title: '商品包装',
          key: 'productPacking',
          align: 'center',
          minWidth: 150,
          type: 'input'
        },
        {
          title: '其他服务承诺',
          key: 'otherPromise',
          align: 'center',
          minWidth: 150,
          type: 'input'
        },
        {
          title: '操作',
          key: 'action',
          align: 'center',
          fixed: 'right',
          minWidth: 100
        }
      ],
      infoData: [],
      skuNoList: [],
      skuNoNotInList: [],
      productUuid: '',
      recordNo: '', // 单据编号
      pusherName: '', // 提交人
      pushTime: '', // 提交时间
      pusherDeptName: '', // 提交部门
      pusherAreaName: '', // 区域
      commitStateStr: '', // "未提交" 单据状态
      reason: '' // 原因
    };
  },
  created () {
    this.fromType = this.$route.query.fromType;
    this.recordNo = this.$route.query.recordNo;
    this.skuNo = this.$route.query.skuNo;
    this.productUuid = this.$route.query.uuid;
    if (this.recordNo) {
      this.getData();
    } else if (this.skuNo) {
      let skuNos = [];
      skuNos.push(this.skuNo);
      this.getInfoData(skuNos);
    } else if (this.productUuid) {
      let skuNos = [];
      skuNos.push(this.productUuid);
      this.getInfoDataProductUuid(skuNos);
    }
  },
  computed: {
    ...mapGetters('permissions/systemBtns', ['showBtn'])
  },
  mounted () {},
  methods: {
    /* 高级关联事件 */
    handleSeniorAssociated () {
      const curBtnId = getBtnsId('高级关联');
      sessionStorage.setItem('buttonId', curBtnId);
      this.seniorAssociated.visible = true;
    },
    /* 获取高级关联结果方法 */
    getSeniorResultFn (data) {
      this.skuRows = []; // 清空关联商品已关联数据
      this.infoData = []; // 清空关联商品带出的表格数据
      this.seniorAssociated.isSenior = true;
      this.getSeniorTableDataAction(data);
    },
    /* 高级关联获取表格数据action请求 */
    getSeniorTableDataAction (params) {
      this.tableLoading = true;
      ApiRequest(
        '/sysback/supplyskurel/multipartGetListBySkuNos',
        'post',
        params
      ).then(res => {
        this.tableLoading = false;
        if (res.retStatus !== '1' || !res.retData) { return false; }
        this.infoData = res.retData;
      }).catch(() => {
        this.tableLoading = false;
      });
    },
    addSkuRows (row) {
      this.skuRows.push(row);
    },
    removeSkuRows (row) {
      this.skuRows = this.skuRows.filter(item => row.uuid != item.uuid);
    },

    // 取消关联
    handleCancelSelect (data) {
      const { index, row } = data;
      this.skuRows = this.skuRows.filter(
        item =>
          (item.skuNo == row.skuNo && item.supplierCode != row.supplyUuid) ||
          (item.skuNo != row.skuNo && item.supplierCode == row.supplyUuid) ||
          item.skuNo != row.skuNo ||
          item.supplierCode != row.supplyUuid
      );
      this.infoData.splice(index, 1);
      this.$Message.info('取消成功', 10);
    },

    getInfoData (data) {
      this.diaVisible = false;
      this.seniorAssociated.isSenior = false;
      const { skuNos, supplyCode } = data;
      if (skuNos.length !== 0) {
        const params = {
          skuNos,
          supplyCodes: supplyCode
        };
        this.tableLoading = true;
        ApiRequest(
          '/sysback/supplyskurel/getListBySkuNos',
          'post',
          params,
          false
        )
          .then(res => {
            this.tableLoading = false;
            if (res.retStatus == '1') {
              this.infoData = res.retData;
            }
          })
          .catch(() => {
            this.tableLoading = false;
          });
      } else {
        this.infoData = [];
      }
    },

    getData () {
      ApiRequest(
        '/sysback/supplyskurel/getUpdateDetailByRecordNo?recordNo=' +
          this.recordNo,
        'post',
        '',
        false
      ).then(res => {
        this.infoData = res.retData.listDetail;
        this.saveinfo = res.retData;
        this.launchReason = res.retData?.launchReason;
        this.infoData.forEach(item => {
          this.skuNoList.push(item.skuNo);
          this.skuNoNotInList.push(item.skuNo);
        });
        // this.viewdata = res.retData;
      });
    },

    // 展示 关联商品 弹窗
    showlinkgoods () {
      let curBtnId = getBtnsId('关联商品');
      sessionStorage.setItem('buttonId', curBtnId);
      this.diaVisible = true;
      this.$refs.link.getLinkData();
    },

    getInfoDataProductUuid (skuNos) {
      ApiRequest(
        '/sysback/supplyskurel/getListByProductUuids?productUuids=' +
          skuNos.join(','),
        'post',
        {},
        false
      ).then(res => {
        if (res.retStatus == '1') {
          this.infoData = this.infoData.concat(res.retData);
        }
      });
    },

    // 表格  多选
    linkSelect (arr) {
      let list = arr;
      this.selectAllList = list;
    },

    nolinkSelect (arr) {
      let list = arr;
      this.selectNoList = list;
    },
    save () {
      if (this.infoData.length > EDIT_SUPPLY_INFO_AMOUNT) {
        return this.$message.warning(`当前单据提交的行数不能超过${EDIT_SUPPLY_INFO_AMOUNT}`)
      }
      let inputList = this.infoData;
      inputList.forEach((item, index) => {
        item.isMainSupply = '2';
      });
      const data = {
        inputList,
        launchReason: this.launchReason // 发起原因
      }
      let recordNo = '';
      if (this.recordNo) {
        recordNo = this.recordNo;
      }
      this.saveLoading = true;
      return new Promise((resolve, reject) => {
        ApiRequest(
          '/sysback/supplyskurel/batchUpdateSupplySkuRel?recordNo=' + recordNo,
          'post',
          data,
          false
        ).then(res => {
          this.saveLoading = false;
          if (res.retStatus == '1') {
            this.saveinfo = res.retData;
            this.recordNo = res.retData.recordNo;
            this.$Message.success('保存成功');
            resolve(true);
          }
        }).catch(() => {
          this.saveLoading = false;
        });
      });
    },
    submit () {
      if (this.saveinfo.recordNo == '') {
        return this.$Message.error('请保存后再提交');
      }
      this.$Modal.confirm({
        title: '提示',
        content: '确认提交供货信息吗？',
        onOk: () => {
          this.submitLoading = true;
          this.save().then(res => {
            if (res) {
              ApiRequest(
                '/sysback/supplyskurel/commitSupplySkuRel?recordNo=' +
                  this.saveinfo.recordNo,
                'post',
                '',
                false
              ).then(res => {
                this.submitLoading = false;
                if (res.retStatus == '1') {
                  this.saveinfo = res.retData;
                  this.footerFields = getFooterFieldFn(res.retData);
                  this.$Message.success('提交成功');
                  this.$router.push({ name: 'chageFromManageList' });
                }
              }).catch(() => {
                this.submitLoading = false;
              });
            }
          });
        },
        onCancel: () => {
          this.submitLoading = false;
        }
      });
    },
    // 导出表格
    exportTable () {
      if (this.infoData.length == 0) {
        return this.$Message.error('请先关联商品');
      }
      let uuid = generateUuid();
      const params = {
        uuid,
        supplyInfo: [...this.infoData]
      }
      this.exportLoading = true;
      const defaultUrl = '/sysback/supplyskurel/downLoadTemplate';
      const seniorUrl = '/sysback/supplyskurel/downLoadTemplate?multipart=1';
      const url = this.seniorAssociated.isSenior ? seniorUrl : defaultUrl;
      ApiRequestExportTable(url, 'post', params, false).then(res => {
        const blob = new Blob([res], {
          type: 'application/octet-stream'
        });
        var link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        link.download = `修改供货信息模板_${uuid}.xlsx`;
        link.click();
        window.URL.revokeObjectURL(blob);
        this.exportLoading = false;
      }).catch(() => {
        this.exportLoading = false;
        this.$Message.error('导出失败');
      });
    },
    // 上传之前
    uploadBefore (e) {
      this.tableLoading = true;
    },
    // 上传失败
    uploadError () {
      this.tableLoading = false;
    },
    // 上传成功
    uploadSuccess (res) {
      this.tableLoading = false;
      const { retData, retStatus, retMessage } = res;
      if (retStatus != 1) {
        return this.$Message.error(retMessage || '导入失败');
      }
      this.$Message.success('导入成功');
      this.infoData = retData;
    },
    // 格式验证错误
    formatError (file, fileList) {
      this.$Message.error('文件格式错误');
      this.tableLoading = false;
    },

    newSpec (row, index) {
      this.infoData[index] = row;
    }
  }
};
</script>
<style lang="less" scoped>
/deep/ .ivu-upload {
  margin: 0 5px;
}
</style>
